<?php
namespace App\Models\System;

use App\Exceptions\ApiException;
use App\Providers\LengthAwarePaginatorProvider;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

/**
* 用户和角色关联表 模型
* @create 2023-08-16 11:30:38
*/
class SysUserRoleModel extends \App\Models\BaseModel {
    use HasFactory;

    const Table                 = "sys_user_role";
    const PrimaryKey    = "user_id";
    public $timestamps  = false;

    static $Wheres = ['user_id', 'role_id'];     // 直接定义column, 默认where(column, '=', value)
    public function __construct($attributes = []) {
        parent::__construct($attributes);

        // static::$Wheres['user_id']   = fn($q, $v) => $q->where(atn('user_id'), '=', $v);
    }



    /** xxxx */
    // public function user() {
        // return $this->hasOne(User::class, 'id', 'uid');
    // }

    /** ========== 常用查询 ========== */
    static $Vo  = ['*', ];
    static $Voi = ['*', ];

    /** 根据UserId获取 */
    public function selectByUserId($user_id, $role_id=null): SysUserRoleModel {
        $where = [['user_id', '=', "{$user_id}"]];
        if ($role_id) $where[] = ['role_id', '=', "{$role_id}"];
        return throw_str(
            static::row($where) ?? "数据($user_id)为空~"
        );
    }
    /** 根据RoleId获取 */
    public function selectByRoleId($role_id): SysUserRoleModel {
        $where = [['role_id', '=', "{$role_id}"]];
        return throw_str(
            static::row($where) ?? "数据($role_id)为空~"
        );
    }


    /** 获取列表 @return SysUserRole[]+paginator() */
    public function selectList(int|array $pag=1, array $param=[]): LengthAwarePaginatorProvider {
        return static::rows_pag($pag, [], fn($q)=>$q
                    // ->when(isset($param['user_id']), fn($q)=>$q->where('user_id', '=', $param['user_id']))
                    ->wheres($param, 'user_id','role_id')
                    ->orderByDesc("user_id")
        );
    }


    /** 插入数据 */
    public function insertData(array $data): SysUserRoleModel {
        return throw_str(
            static::row_add([
                // 'user_id'            => $data['user_id'],
                // 'role_id'            => $data['role_id'],
            ])
        );
    }


    /** 更新数据 */
    public function updateData(int|array $idOrWhere, array $data): SysUserRoleModel {
        $values = static::when(
                    $data, 
                    // 'user_id',
                    // 'role_id',
                );
        return throw_str(
            static::row_update($idOrWhere, $values)
        );
    }


    /** 删除数据 */
    public function deleteData(int|array $idOrWhere): SysUserRoleModel {
        return throw_str(
            static::row_delete($idOrWhere)
        );
    }



}